<?php

namespace app\admin\model;

use think\facade\Cache;
use think\Model;

class AdminRoleModel extends Model
{
    protected $table = '__ADMIN_ROLE__';

    public function getAllRole()
    {
        $all_role = $this->order('id asc')->select()->toArray();
        return $all_role;
    }

    public function getRole($id)
    {
        $role = $this->find($id);
        if (empty($role)) {
            return '';
        } else {
            return $role->toArray();
        }
    }

    public function roleAdd($post_data)
    {
        if (!empty($post_data['ids'])) {
            $post_data['auth'] = implode(',', $post_data['ids']);
        }
        if ($this->allowField(true)->save($post_data)) {
            return ['status' => 'y', 'info' => '角色添加成功'];
        } else {
            return ['status' => 'n', 'info' => '角色添加失败'];
        }
    }

    public function roleEdit($post_data)
    {
        if ($post_data['id'] == 1) {
            return ['status' => 'n', 'info' => '超级管理员不允许被此操作'];
        }

        if (!empty($post_data['ids'])) {
            $post_data['auth'] = implode(',', $post_data['ids']);
        } else {
            $post_data['auth'] = '';
        }

        if (false !== $this->allowField(true)->save($post_data, ['id' => $post_data['id']])) {
            Cache::rm('role' . $post_data['id']);
            return ['status' => 'y', 'info' => '角色修改成功'];
        } else {
            return ['status' => 'n', 'info' => '角色修改失败'];
        }
    }

}